﻿using DeHeng_Mes.Constant;
using DeHeng_Mes.Dao.PlcDao;
using DeHeng_Mes.Model.BossModel;
using DeHeng_Mes.Model.ConfigModel;
using DeHeng_Mes.Model.OrderSingleton;
using DeHeng_Mes.Model.PlcModel;
using DeHeng_Mes.Model.Singleton;
using DeHeng_Mes.Utils;
using S7.Net;
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Documents;

namespace DeHeng_Mes.Service.Plc
{
    #region 数据读取线程
    #endregion
    /// <summary>
    /// 下发工厂订单给Plc
    /// </summary>
    public class LineMesToPlc
    {
        #region 成员实例
        List<PlcOrderConfigModel> readPlcList = PlcOrderConfigModelList.ReadPlcList;
        #endregion

        public (string, string, string) OrderToPlc(OrderPlan orderPlan, DateTime now)
        {
            if (PlcConnectionManager.plcContainer?.Count > 0)
            {
                try
                {
                    // 获取该物料对应的PlcName
                    string name = MappingTable.GetPlcNameByMaterial(orderPlan.material_id);

                    List<string> plcNames = name.Split(',').ToList();

                    string message = $"工单配置成功，工单号为[{orderPlan.wo_code}]，数量为[{orderPlan.plan_num}]，物料名称为[{orderPlan.material_name}]，已存在{OrderSingleton.GetCount()}个工单";

                    if (!(plcNames?.Count > 0))
                        return ("0", "失败，未映射", "");

                    foreach (var plcName in plcNames)
                    {
                        OrderSingleton.AddOrder(new OrderSingletonModel()
                        {
                            LineName = orderPlan.eqpt_id,
                            MaterialId = orderPlan.material_id,
                            MaterialName = orderPlan.material_name,
                            OrderId = orderPlan.wo_code,
                            ProducessNum = orderPlan.plan_num,
                            ProducessNumNow = 0,
                            Status = orderPlan.wo_status,
                            PlcName = plcName,
                            OrderCreateTime = now
                        });
                    }

                    Tools.ProduceLogText(message);

                    return ("1", message, name);
                }
                catch (KeyNotFoundException ex)
                {
                    Tools.ProduceLogTextError($"工单下发失败：原因是{ex.Message}");

                    OrderClear(orderPlan.wo_code);

                    // 失败响应
                    return ("0", $"工单下发失败：{ex.Message}", "");
                }
                catch (InvalidOperationException ex)
                {
                    Tools.ProduceLogTextError($"工单下发失败：原因是{ex.Message}");

                    OrderClear(orderPlan.wo_code);

                    // 失败响应
                    return ("0", $"工单下发失败：{ex.Message}", "");
                }
                catch (Exception ex)
                {
                    Tools.ProduceLogTextError($"工单下发失败：原因是{ex.Message}");

                    OrderClear(orderPlan.wo_code);

                    // 失败响应
                    return ("0", "工单下发失败：内部错误", "");
                }
            }
            else
            {
                Tools.ProduceLogTextError($"工单下发失败：原因是PLC实例未配置");

                // 失败响应
                return ("0", "工单下发失败：内部错误", "");
            }
        }

        /// <summary>
        /// 清除工单
        /// </summary>
        /// <param name="material_id"></param>
        public void OrderClear(string wo_code)
        {
            // 删除匹配的数据
            OrderSingleton.RemoveByOrderId(wo_code);
        }

        /// <summary>
        /// 根据物料编码获取符合条件的Plc实例
        /// </summary>
        /// <param name="material_id"></param>
        private PlcConfigModel GetPlc(string plcName)
        {
            PlcConfigModel plcConfigModel = PlcConnectionManager.plcContainer.Where(x => x.name == plcName).FirstOrDefault();

            if (plcConfigModel != null)
            {
                if (plcConfigModel.isConnected)
                {
                    return plcConfigModel;
                }
                else
                {
                    throw new InvalidOperationException("Plc未连接");
                }
            }
            else
            {
                throw new KeyNotFoundException("物料不匹配");
            }
        }
    }

}
